import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import dayjs from "dayjs";
import { computed, h, markRaw, onMounted, reactive, ref } from "vue";
import RejectProject from "../form/RejectProject.vue";
// api
import { getApprovalCount } from "@/api/other/approval";
import { checkPlatApply, getPlatApplyList } from "@/api/other/platApply"; // 平台申请
import { checkResearch, getResearchList } from "@/api/other/researchTeam"; // 科研团队
import {
  checkTeacherAchiev,
  getTeacherAchievList
} from "@/api/other/teacherAchiev"; // 教学成果
import { checkAchiev, getAchievList } from "@/api/research/achiev"; // 科研成果
import {
  checkAchievTrans,
  getAchievTransList
} from "@/api/research/achievTrans"; // 成果转化
import { checkOtherAward, getOtherAwardList } from "@/api/research/award"; // 科研获奖
import { checkPaper, getPaperList } from "@/api/research/paper"; // 论文
import { checkPatent, getPatentList } from "@/api/research/patent"; // 专利
import { checkProject, getProjectList } from "@/api/research/project"; // 横向、纵向项目

// page
import PlatApplyDetail from "@/views/platApply/home/form/showDetail.vue";
import AchievDetail from "@/views/research/achiev/detail/index.vue";
import AchievTransDetail from "@/views/research/achievTrans/form/showDetail.vue";
import AwardDetail from "@/views/research/award/form/showDetail.vue";
import HorizontalDetail from "@/views/research/horizontal/form/showDetail.vue";
import LongitudinalDetail from "@/views/research/longitudinal/form/showDetail.vue";
import PaperDetail from "@/views/research/paper/form/showDetail.vue";
import PatentDetail from "@/views/research/patent/form/showDetail.vue";
import TeacherAchievDetail from "@/views/teacherAchiev/home/form/showDetail.vue";
import ResearchTeamDetail from "@/views/team/research/detail/index.vue";
import { ElMessageBox } from "element-plus";

export function useApproval() {
  const form = reactive({
    examineStatus: 0,
    orderBy: "asc",
    pageNum: 1,
    pageSize: 999
  });
  const currentData = ref<any>({});
  const dataList = ref([]);
  const loading = ref(true);
  const treeData = ref([]);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const checkForm = ref<any>({});
  const detailType = ref(1);
  const tabType = ref("kycg");
  const tabList = ref([
    { label: "科研成果", name: "kycg", count: 0 },
    { label: "论文", name: "lw", count: 0 },
    { label: "横向项目", name: "hxxm", count: 0 },
    { label: "纵向项目", name: "zxxm", count: 0 },
    { label: "专利", name: "zl", count: 0 },
    { label: "科研获奖", name: "qtkjhj", count: 0 },
    { label: "科研团队", name: "kytd", count: 0 },
    { label: "平台申报", name: "ptsb", count: 0 },
    { label: "教学成果", name: "jxcg", count: 0 },
    { label: "成果转化", name: "cgzh", count: 0 }
  ]);
  // 每个模块对应的字段、方法
  const moduleMap = {
    kycg: {
      title: "scrAchievementsName",
      component: AchievDetail,
      getListFun: getAchievList,
      doApprivalFun: checkAchiev
    },
    lw: {
      title: "paperName",
      component: PaperDetail,
      getListFun: getPaperList,
      doApprivalFun: checkPaper
    },
    hxxm: {
      title: "verticalProjectName",
      component: HorizontalDetail,
      moduleParams: { projectType: 2 }, // 项目类型 1纵向 2横向
      getListFun: getProjectList,
      doApprivalFun: checkProject
    },
    zxxm: {
      title: "verticalProjectName",
      component: LongitudinalDetail,
      moduleParams: { projectType: 1 }, // 项目类型 1纵向 2横向
      getListFun: getProjectList,
      doApprivalFun: checkProject
    },
    zl: {
      title: "patentName",
      component: PatentDetail,
      getListFun: getPatentList,
      doApprivalFun: checkPatent
    },
    qtkjhj: {
      title: "obtainRewardAchievementName",
      component: AwardDetail,
      getListFun: getOtherAwardList,
      doApprivalFun: checkOtherAward
    },
    kytd: {
      title: "teamName",
      component: ResearchTeamDetail,
      getListFun: getResearchList,
      doApprivalFun: checkResearch
    },
    ptsb: {
      title: "writeObjective",
      component: PlatApplyDetail,
      getListFun: getPlatApplyList,
      doApprivalFun: checkPlatApply
    },
    jxcg: {
      title: "achievementsName",
      component: TeacherAchievDetail,
      getListFun: getTeacherAchievList,
      doApprivalFun: checkTeacherAchiev
    },
    cgzh: {
      title: "patentName",
      component: AchievTransDetail,
      getListFun: getAchievTransList,
      doApprivalFun: checkAchievTrans
    }
  };
  const approvalList = ref([]);
  const approvalColumns: TableColumnList = [
    {
      label: "节点名称",
      prop: "submitName",
      minWidth: 100
    },
    {
      label: "审核人",
      prop: "updateUserName",
      minWidth: 100
    },
    {
      label: "审核结果",
      prop: "barCode",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <div>
          {row.examineStatus === 0 ? (
            <el-tag type="warning">审核中</el-tag>
          ) : row.examineStatus === 1 ? (
            <el-tag type="primary">已审核</el-tag>
          ) : (
            <el-tag type="danger">已驳回</el-tag>
          )}
        </div>
      )
    },
    {
      label: "审核意见",
      prop: "goodsType",
      minWidth: 120,
      formatter: ({ examineDesc }) => examineDesc || "--"
    },
    {
      label: "审核时间",
      prop: "avgBuyPrice",
      minWidth: 100,
      formatter: ({ gmtModified }) =>
        dayjs(gmtModified).format("YYYY-MM-DD HH:mm")
    }
  ];

  const currentComponent = computed(() => {
    let moduleVal = moduleMap[tabType.value];
    return markRaw(moduleVal.component);
  });

  const getTitleName = item => {
    let moduleVal = moduleMap[tabType.value];
    let titleKey = moduleVal.title;
    return item[titleKey] || "--";
  };

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    form.pageNum = val;
    onSearch();
  }

  const tabChange = () => {
    onSearch();
  };

  async function onSearch() {
    loading.value = true;
    currentData.value = {};

    let moduleVal = moduleMap[tabType.value];
    const { data } = await moduleVal.getListFun(
      moduleVal.moduleParams ? { ...form, ...moduleVal.moduleParams } : form
    );
    dataList.value = data.records || [];
    if (dataList.value.length > 0) {
      currentData.value = dataList.value[0];
    }
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;

    setTimeout(() => {
      loading.value = false;
    }, 200);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  const doPass = row => {
    ElMessageBox.confirm("是否确认审核通过?", "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true
    }).then(async () => {
      let params = {
        id: row.id,
        examineStatus: 1
      };
      console.log("params ", params);
      await moduleMap[tabType.value].doApprivalFun(params);
      message("已审核通过", { type: "success" });
      loadApprovalTotal();
      onSearch();
    });
  };

  const passForm = ref();
  const approvalPass = row => {
    // 科研成果、科研团队 不需要填写积分
    if (["kycg", "kytd"].includes(tabType.value)) {
      doPass(row);
      return;
    }

    addDialog({
      title: "审核通过",
      props: {
        optType: 1,
        score: row.score
      },
      width: "500px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(RejectProject, { ref: passForm }),
      beforeSure: done => {
        const FormRef = passForm.value.getRef();
        FormRef.validate(async valid => {
          if (valid) {
            let formVal = passForm.value.getForm();
            formVal.id = row.id;
            formVal.examineStatus = 1;
            console.log("formVal ", formVal);
            await moduleMap[tabType.value].doApprivalFun(formVal);
            message("已审核通过", { type: "success" });
            loadApprovalTotal();
            onSearch();
            done();
          }
        });
      }
    });
  };

  const rejectForm = ref();
  const approvalReject = row => {
    addDialog({
      title: "驳回理由",
      props: {
        optType: 2,
        score: row.score,
        examineDesc: row.examineDesc || ""
      },
      width: "500px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(RejectProject, { ref: rejectForm }),
      beforeSure: done => {
        const FormRef = rejectForm.value.getRef();
        FormRef.validate(async valid => {
          if (valid) {
            let formVal = rejectForm.value.getForm();
            formVal.id = row.id;
            formVal.examineStatus = 2;
            console.log("formVal ", formVal);
            await moduleMap[tabType.value].doApprivalFun(formVal);
            message("已驳回", { type: "success" });
            loadApprovalTotal();
            onSearch();
            done();
          }
        });
      }
    });
  };

  // 获取统计数量
  const loadApprovalTotal = async () => {
    let { data } = await getApprovalCount();
    let tempTabList = [
      {
        label: "科研成果",
        name: "kycg",
        count: data.scrAchievementsCount || 0
      },
      { label: "论文", name: "lw", count: data.paperCount || 0 },
      {
        label: "横向项目",
        name: "hxxm",
        count: data.horizontalProjectsCount || 0
      },
      {
        label: "纵向项目",
        name: "zxxm",
        count: data.longitudinalProjectsCount || 0
      },
      { label: "专利", name: "zl", count: data.patentsCount || 0 },
      {
        label: "科研获奖",
        name: "qtkjhj",
        count: data.otherObtainRewardCount || 0
      },
      { label: "科研团队", name: "kytd", count: data.researchTeamCount || 0 },
      {
        label: "平台申报",
        name: "ptsb",
        count: data.platformDeclarationCount || 0
      },
      {
        label: "教学成果",
        name: "jxcg",
        count: data.teachingAchievementsCount || 0
      },
      {
        label: "成果转化",
        name: "cgzh",
        count: data.achievementTransformation || 0
      }
    ];
    tabList.value = tempTabList;
  };

  onMounted(async () => {
    loadApprovalTotal();

    onSearch();
  });

  return {
    form,
    loading,
    dataList,
    treeData,
    selectedNum,
    pagination,
    deviceDetection,
    tabType,
    detailType,
    tabList,
    moduleMap,
    checkForm,
    currentComponent,
    currentData,
    approvalList,
    approvalColumns,
    getTitleName,
    tabChange,
    onSearch,
    resetForm,
    approvalPass,
    approvalReject,
    handleSizeChange,
    handleCurrentChange
  };
}
